import { fileURLToPath, URL } from "node:url";
import vueSetupExtend from "vite-plugin-vue-setup-extend";
import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import Components from "unplugin-vue-components/vite";
import { VantResolver } from "@vant/auto-import-resolver";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import path from "path";
import mockDevServerPlugin from "vite-plugin-mock-dev-server";

import { createHtmlPlugin } from "vite-plugin-html";
import { enableCDN } from "./build/cdn";

import dayjs from "dayjs"; // 引入时间格式化库

import { visualizer } from "rollup-plugin-visualizer"; // 打包分析工具
import viteCompression from "vite-plugin-compression"; // Gzip/Brotli 压缩插件

import AutoImport from "unplugin-auto-import/vite";

// 当前工作目录路径
const root = process.cwd();

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  // 环境变量
  const env = loadEnv(mode, process.cwd());
  const timestamp = dayjs().format("YYYYMMDDHHmmss"); // 生成时间戳

  return {
    base: env.VITE_BASE_URL || "/",
    plugins: [
      vue(),
      vueJsx(),
      Components({
        resolvers: [VantResolver()]
      }),
      AutoImport({
        imports: ["vue", "vue-router", "vue-i18n"],
        dts: "src/auto-imports.d.ts"
      }),
      // 允许 setup 语法糖上添加组件名属性
      vueSetupExtend(),
      // svg icon
      createSvgIconsPlugin({
        // 指定图标文件夹
        iconDirs: [path.resolve(root, "src/icons/svg")],
        // 指定 symbolId 格式
        symbolId: "icon-[dir]-[name]"
      }),
      mockDevServerPlugin(),
      // 注入模板数据
      createHtmlPlugin({
        inject: {
          data: {
            ENABLE_ERUDA: env.VITE_ENABLE_ERUDA || "false"
          }
        }
      }),
      // 生产环境默认不启用 CDN 加速
      enableCDN(env.VITE_CDN_DEPS),
      // 打包分析插件
      visualizer({
        open: true,
        gzipSize: true,
        brotliSize: true
      }),
      // Gzip/Brotli 压缩插件
      viteCompression({
        algorithm: "gzip", // 可选 'brotliCompress'
        ext: ".gz",
        threshold: 10240, // 压缩文件大小阈值（单位：字节）
        deleteOriginFile: false // 是否删除原文件
      })
    ],
    resolve: {
      alias: {
        "~": path.resolve(__dirname, "./"),
        "@": path.resolve(__dirname, "./src")
      },
      extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"]
    },
    server: {
      host: "0.0.0.0",
      port: Number(env.VITE_APP_PORT),
      open: true, // 是否自动打开浏览器
      proxy: {
        [env.VITE_APP_BASE_API]: {
          target:
            env.VITE_NODE_ENV === "development"
              ? `http://8.136.178.249:8090/environmental-assistant/api`
              : `http://8.136.178.249:8090/environmental-assistant/api`,
          changeOrigin: true,
          rewrite: path =>
            path.replace(new RegExp(`^${env.VITE_APP_BASE_API}`), "")
        }
      },
      hmr: {
        overlay: true
      }
    },
    build: {
      minify: "terser",
      assetsDir: "./",
      outDir: "dist",
      terserOptions: {
        compress: {
          drop_console: true, // 移除 console.log
          drop_debugger: true // 移除 debugger
        }
      },
      cssCodeSplit: true,
      chunkSizeWarningLimit: 2000,
      rollupOptions: {
        input: "index.html",
        output: {
          chunkFileNames: "static/js/[name]-[hash].js",
          entryFileNames: "static/js/[name]-[hash].js",
          assetFileNames: assetInfo => {
            if (assetInfo.name.endsWith(".css")) {
              return `static/css/[name]-${timestamp}.[ext]`;
            }
            if (
              ["png", "jpg", "svg", "PNG", "jpeg"].some(ext =>
                assetInfo.name.endsWith(ext)
              )
            ) {
              return `static/img/[name]-${timestamp}.[ext]`;
            }
            if (
              ["ttf", "woff", "woff2"].some(ext => assetInfo.name.endsWith(ext))
            ) {
              return `static/fonts/[name]-${timestamp}.[ext]`;
            }
            return `static/assets/[name]-${timestamp}.[ext]`;
          },
          manualChunks(id) {
            if (id.includes("node_modules")) {
              if (id.includes("element-plus")) {
                return "vendor-element-plus";
              }
              if (id.includes("vue")) {
                return "vendor-vue";
              }
              return "vendor";
            }
          }
        }
      },
      sourcemap: true // 开启 Source Map
    }
  };
});
